<template>
  <BackCommonBreadcrumb>
    <span class="btn search" @click="search">查询</span>
    <span class="btn reset" @click="reset">重置</span>
    <span class="btn add" @click="add">新增</span>
  </BackCommonBreadcrumb>
  <BackSearchForm :model="data.queryParams">
    <el-form-item label="公司名称">
      <el-input v-model="data.queryParams.name" clearable />
    </el-form-item>
    <el-form-item label="负责人联系方式">
      <el-input v-model="data.queryParams.principalPhone" clearable />
    </el-form-item>
  </BackSearchForm>
  <BackSimpleTable ref="simpleTable" :_configs="configs" :_data="data.dataList" :_total="data.total" @_load="loadTableData">
    <template #opt>
      <el-table-column v-slot="{ row }" prop="opt" label="操作" width="200">
        <span v-if="row.status === 0" class="link edit" @click="updateStatus(row.id, 1)">激活</span>
        <span v-if="row.status === 1" class="link edit" @click="updateStatus(row.id, 9)">注销</span>
        <span v-if="row.status === 9" class="link edit" @click="updateStatus(row.id, 1)">恢复运营</span>
        <span class="link edit" @click="edit(row)">编辑</span>
        <span class="link del" @click="del(row)">删除</span>
      </el-table-column>
    </template>
  </BackSimpleTable>
  <BackSimpleDialog v-model="addForm.dialogShow" :close-on-click-modal="false" :destroy-on-close="true" :close="cancel" width="800px">
    <template #header><span>{{ addForm.dialogTitle }}</span></template>
    <template #default>
      <el-form
          ref="addCompanyForm"
          label-position="right"
          label-width="120px"
          :rules="addCompanyFormRules"
          :model="addForm.formParams"
      >
        <el-form-item label="公司名称" prop="name" required>
          <el-input v-model="addForm.formParams.name" maxlength="30" />
        </el-form-item>
        <el-form-item label="公司简称" prop="shortName">
          <el-input v-model="addForm.formParams.shortName" max="10" />
        </el-form-item>
        <el-form-item label="负责人" prop="principal" required>
          <el-input v-model="addForm.formParams.principal" maxlength="6" />
        </el-form-item>
        <el-form-item label="负责人联系方式" prop="principalPhone" required>
          <el-input v-model="addForm.formParams.principalPhone" />
        </el-form-item>
        <el-form-item label="工商注册号" prop="registrationSn">
          <el-input v-model="addForm.formParams.registrationSn" />
        </el-form-item>
        <el-form-item label="系统名称" prop="sysName" required>
          <el-input v-model="addForm.formParams.sysName" />
        </el-form-item>
        <el-form-item label="前端部署地址" prop="url" required>
          <el-input type="url" v-model="addForm.formParams.url" />
        </el-form-item>
        <el-form-item label="运营到期时间" prop="deadline" required>
          <el-input type="date" v-model="addForm.formParams.deadline" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addForm.formParams.address" readonly />
        </el-form-item>
          <AMapPainting :plugins="['PlaceSearch']" :height="240" :defaultMarker="addForm.marker" @_placeSearch="selectPlace" />
      </el-form>
    </template>
    <template #footer>
      <span class="btn cancel" @click="cancel(addCompanyForm)">取消</span>
      <span class="btn confirm" @click="confirm(addCompanyForm)">确认</span>
    </template>
  </BackSimpleDialog>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"
import { validatePhone, clearObjectFields, splitAddress } from "@/utils/helpers"

const { proxy }: any = getCurrentInstance()

const data = reactive({
  queryParams: {
    name: void 0,
    principalPhone: void 0
  },
  total: 0,
  dataList: []
})

const simpleTable = ref()

const configs = [
  {
    prop: 'name',
    label: '公司名称'
  },
  {
    prop: 'principal',
    label: '公司负责人'
  },
  {
    prop: 'principalPhone',
    label: '负责人联系方式'
  },
  {
    prop: '-',
    label: '行政区',
    formatter: (row: any, value: any) => {
      return row.province + row.city + row.area
    }
  },
  {
    prop: 'url',
    label: '前端地址'
  },
  {
    prop: 'deadline',
    label: '运营到期时间'
  },
  {
    prop: 'status',
    label: '状态',
    formatter: (row: any, value: any) => {
      if (row.status === 0) return '建设中'
      if (row.status === 1) return '运营中'
      if (row.status === 9) return '已注销'
}
  }
]

const search = () => {
  simpleTable.value._init()
}

const reset = () => {
  data.queryParams.name = void 0
}

const addCompanyForm = ref()

const addCompanyFormRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入用户公司名称！', trigger: '' }],
  principal: [{ required: true, message: '请输入用户公司名称！', trigger: '' }],
  principalPhone: [{ validator: validatePhone, trigger: 'blur' }],
  sysName: [{ required: true, message: '请输入系统名称！', trigger: '' }],
  url: [{ required: true, message: '请输入前端部署地址！', trigger: '' }],
  deadline: [{ required: true, message: '请输入运营到期时间！', trigger: '' }]
})

const addForm = reactive<any>({
  dialogShow: false,
  formType: 1,
  dialogTitle: '',
  marker: null,
  formParams: {
    id: void 0,
    name: void 0,
    shortName: void 0,
    principal: void 0,
    principalPhone: void 0,
    registrationSn: void 0,
    province: void 0,
    city: void 0,
    area: void 0,
    address: void 0,
    lng: void 0,
    lat: void 0,
    sysName: void 0,
    url: void 0,
    logo: void 0,
    deadline: void 0,
    status: 0,
    type: 1
  }
})

const selectPlace = (address: any, pos: any[]) => {
  addForm.formParams.address = address
  let district = splitAddress(address)
  if (district) {
    if (district[0]) addForm.formParams.province = district[0]
    if (district[1]) addForm.formParams.city = district[1]
    if (district[2]) addForm.formParams.area = district[2]
  }
  addForm.formParams.lng = pos[0]
  addForm.formParams.lat = pos[1]
}

const resetAddForm = () => {
  clearObjectFields(addForm.formParams)
}

const add = () => {
  resetAddForm()
  addForm.marker = null
  addForm.dialogTitle = '添加公司信息'
  addForm.formType = 1
  addForm.dialogShow = true
}

const edit = (row: any) => {
  resetAddForm()
  addForm.formParams.id = row.id
  addForm.formParams.name = row.name
  addForm.formParams.shortName = row.shortName
  addForm.formParams.principal = row.principal
  addForm.formParams.principalPhone = row.principalPhone
  addForm.formParams.registrationSn = row.registrationSn
  addForm.formParams.address = row.address
  addForm.formParams.lng = row.lng
  addForm.formParams.lat = row.lat
  addForm.formParams.sysName = row.sysName
  addForm.formParams.url = row.url
  addForm.formParams.logo = row.logo
  addForm.formParams.deadline = row.deadline
  addForm.marker = [row.lng, row.lat]
  addForm.dialogTitle = '编辑公司信息'
  addForm.formType = 2
  addForm.dialogShow = true
}

const del = (row: any) => {
  ElMessage.warning('暂不支持直接删除公司信息！')
}

const cancel = async (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields()
  }
  addForm.dialogShow = false
}

const updateStatus = (id: any, status: any) => {
  proxy.$API.companyApi.updateCompanyStatus({ id, status }).then((res: any) => {
    if (res.code && res.code === 10000) {
      ElMessage.success('更新成功！')
      search()
    } else {
      ElMessage.error(res.msg || '更新失败！')
    }
  })
}

const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (addForm.formType === 1) {
    await formEl.validate((valid, fields) => {
      if (valid) {
        proxy.$API.companyApi.insertCompany({ ...addForm.formParams }).then((res: any) => {
          if (res.code && res.code === 10000) {
            ElMessage.success('添加成功！')
            addForm.dialogShow = false
            search()
          } else {
            ElMessage.error(res.msg || '添加失败！')
          }
        })
      }
    })
  } else {
    await formEl.validate((valid, fields) => {
      if (valid) {
        proxy.$API.companyApi.updateCompany({ ...addForm.formParams }).then((res: any) => {
          if (res.code && res.code === 10000) {
            ElMessage.success('编辑成功！')
            addForm.dialogShow = false
            search()
          } else {
            ElMessage.error(res.msg || '编辑失败！')
          }
        })
      }
    })
  }
}

const loadTableData = (pageNum?: number, pageSize?: number) => {
  proxy.$API.companyApi.queryCompanyPage({ ...data.queryParams, pageNum, pageSize }).then((res: any) => {
    data.dataList = res.records ?? []
    data.total = res.total ?? 0
  })
}
</script>

